// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections.Generic;
using System.Linq;

namespace SnapObjects.Data
{
    internal static class DynamicModelHelp
    {
        public static Type GetPropertyType(Type type)
        {
            if ((type.IsPrimitive || type.IsValueType) && Nullable.GetUnderlyingType(type) == null)
            {
                type = typeof(Nullable<>).MakeGenericType(type);
            }

            return type;
        }

        public static string GetValidPropertyName(string name, IDictionary<string, Type> properties)
        {
            if (String.IsNullOrWhiteSpace(name) || properties.ContainsKey(name))
            {
                name = RebuildName(name, properties);
            }

            return name;
        }

        public static bool CheckType(string name, Type type)
        {
            if (type == null)
            {
                throw new Exception(String.Format(Properties.Resource.DATATYPE_NOTSUPPORT, name));
            }

            return true;
        }

        public static string GetValidPropertyName(string name, IDictionary<string, IDynamicProperty> properties)
        {
            if (String.IsNullOrWhiteSpace(name) || properties.ContainsKey(name))
            {
                name = RebuildName(name, properties);
            }

            return name;
        }

        private static string RebuildName(string name, IDictionary<string, Type> properties)
        {
            var index = 0;
            var tempName = name;

            if (String.IsNullOrWhiteSpace(name))
            {
                tempName = "COMPUTE_";
            }
            else if (properties.ContainsKey(name))
            {
                tempName += "_";
            }
            else
            {
                return name;
            }

            name = tempName + index;

            while (properties.ContainsKey(name))
            {
                index++;
                name = tempName + index;
            }

            return name;
        }

        private static string RebuildName(string name, IDictionary<string, IDynamicProperty> properties)
        {
            var index = 0;
            var tempName = name;

            if (String.IsNullOrWhiteSpace(name))
            {
                tempName = "COMPUTE_";
            }
            else if (properties.ContainsKey(name))
            {
                tempName += "_";
            }
            else
            {
                return name;
            }

            name = tempName + index;

            while (properties.ContainsKey(name))
            {
                index++;
                name = tempName + index;
            }

            return name;
        }
    }
}
